import { PlusOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { Button, Row, Space, Tooltip } from 'antd';
import type { ColumnType } from 'antd/lib/table';
import { useEffect, useState } from 'react';

import api from '@/apis/api';
import AddUserModal from '@/components/AddUserModal';
import ChangePinCodeModal from '@/components/ChangePinCodeModal';
import CustomTable from '@/components/CustomTable';
import DeleteUserModal from '@/components/DeleteUserModal';
import LocalInfo from '@/utils/localInfo';

import styles from './styles.module.less';

type TableData = {
  id: number;
  name: string;
  grant: number;
  timestamp: string;
  login: boolean;
};

export default function UserManagement() {
  const [userId, setUserId] = useState<number>(0);
  const [userName, setUserName] = useState<string>('');
  const [isaddModalOpen, setIsaddModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isChangePinModalOpen, setIsChangePinModalOpen] = useState(false);
  // 记录总数
  const [total, setTotal] = useState<number>(0);
  // 记录页码
  const [page, setPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);

  const [usersTable, setUsersTable] = useState<TableData[]>([
    // {
    //   id: 1,
    //   name: 'admin',
    //   grant: 0,
    //   timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    //   login: true,
    // },
  ]);

  const columns: (ColumnType<TableData> & { align?: 'left' | 'right' | 'center' })[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '4%',
      align: 'center',
      render: (_text, _record, index) => index + 1,
    },
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
      width: '5%',
      align: 'center',
      render: (text) => {
        const currentUserName = LocalInfo.getCurrentUserName();
        const title = currentUserName === text ? '本机用户' : '其他用户';
        return (
          <Tooltip title={title} color={'#0179FE'}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      width: '5%',
      align: 'center',
      render: (_, text) => {
        return text.grant === 0 ? '管理员' : '操作员';
      },
    },

    // {
    //   title: '时间',
    //   dataIndex: 'timestamp',
    //   key: 'timestamp',
    //   width: '5%',
    //   align: 'center',
    //   render: (data) => {
    //     const d = data ? dayjs(data).format('YYYY-MM-DD HH:mm:ss') : '';
    //     return d;
    //   },
    // },
    {
      title: '登录状态',
      dataIndex: 'loginState',
      key: 'loginState',
      width: '5%',
      align: 'center',
      render: (_, text) => {
        return text.login ? '已登录' : '未登录';
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (record) => {
        const handleClick = () => {
          setIsDeleteModalOpen(true);
          setUserId(record.id);
        };
        const handelChangeClick = () => {
          setIsChangePinModalOpen(true);
          setUserId(record.id);
          setUserName(record.name);
        };
        const isDisabled = LocalInfo.getRoleId() === 2;
        const disabledStyle = {
          color: 'rgba(0, 0, 0, 0.25)',
          cursor: 'not-allowed',
          pointerEvents: 'none' as 'none', // 使用类型断言
        };
        return (
          <>
            <Space>
              <a
                onClick={handelChangeClick}
                style={isDisabled ? disabledStyle : undefined}
              >
                修改用户密码
              </a>
              |
              <a onClick={handleClick} style={isDisabled ? disabledStyle : undefined}>
                删除
              </a>
            </Space>
          </>
        );
      },
      width: '5%',
      align: 'center',
    },
  ];

  const { data: usersData } = useQuery({
    queryKey: ['getUsersData', { page, pageSize }],
    queryFn: async () => {
      const res: any = await api.GetUsersData({
        skip: (page - 1) * pageSize,
        take: pageSize,
      });
      return res.data;
    },
  });

  useEffect(() => {
    if (usersData) {
      setTotal(usersData.total);
      setUsersTable(usersData.items);
    }
  }, [usersData]);

  return (
    <>
      <div
        className={styles.Table}
        style={{
          background: '#fff',
          padding: '25px',
          marginBottom: '25px',
          marginTop: '-24px',
        }}
      >
        {/* 按钮 */}
        <Row>
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              style={{ marginTop: '-8px', marginBottom: '17px', width: '100px' }}
              onClick={() => setIsaddModalOpen(true)}
              disabled={LocalInfo.getRoleId() === 2}
            >
              添加用户
            </Button>
          </div>
        </Row>
        <CustomTable
          total={total}
          page={page}
          pageSize={pageSize}
          setPage={setPage}
          setPageSize={setPageSize}
          dataSource={usersTable}
          columns={columns}
          scroll={{ x: 800, y: 800 }}
          rowClassName={(_record, index) => (index % 2 === 0 ? 'even-row' : 'odd-row')}
          rowKey="id"
        />
        <AddUserModal visible={isaddModalOpen} setVisible={setIsaddModalOpen} />
        <DeleteUserModal
          visible={isDeleteModalOpen}
          setVisible={setIsDeleteModalOpen}
          userId={userId}
          total={total}
          page={page}
          pageSize={pageSize}
          setPage={setPage}
        />
        <ChangePinCodeModal
          userId={userId}
          userName={userName}
          visible={isChangePinModalOpen}
          setVisible={setIsChangePinModalOpen}
        />
      </div>
    </>
  );
}
